package cn.kbyue.security.security;

import cn.kbyue.security.entity.KbUser;
import cn.kbyue.security.entity.enums.UserStatusEnum;
import java.util.Collection;
import java.util.Objects;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * security 专用用户
 *
 * @author xlang
 * @version 0.0.1
 * @date 2021/9/14 18:56
 */
@Data
public class DefinedUserDetails implements UserDetails {

    private transient KbUser user;

    private transient Collection<GrantedAuthority> authorities;

    public DefinedUserDetails(KbUser user, Collection<GrantedAuthority> authorities) {
        this.user = user;
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    @Override
    public String getUsername() {
        return this.user.getAccount();
    }

    /**
     * 账号是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        boolean expired = Objects.equals(this.user.getStatus(), UserStatusEnum.EXPIRED.getCode());
        return !expired;
    }

    /**
     * 账号是否锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        boolean locked = Objects.equals(this.user.getStatus(), UserStatusEnum.LOCKED.getCode());
        return !locked;
    }

    /**
     * 密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否禁用
     */
    @Override
    public boolean isEnabled() {
        boolean disable = Objects.equals(this.user.getStatus(), UserStatusEnum.DISABLE.getCode());
        return !disable;
    }
}

